package real.realschool;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

import real.ebook.EbookActivity;

import com.example.testalram.Alarms;
import com.example.testalram.SetAlarm;
import com.example.testalram.SettingsActivity;
import com.google.android.gcm.GCMRegistrar;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RealActivity extends Activity {

	public static StaticAct Activity = new StaticAct(); // Activity 생성
	
	Button school, college, talk, ebook;
	ImageView timer;
	
	LinearLayout li ,li_rice;
	NotificationManager nNotificationManager;
	
	int checknum = 0;
	public String food_lunch, food_dinner;
	
	String date;
	TextView rice;
	Spinner sp;
	List<String> score_list;
	ArrayAdapter rice_adapter;
	String sp_check;
	SQLiteOpenHelper dbHelper;
	SQLiteDatabase db;
	String score; // 도시락 평점
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
			
		Activity.at.add(this); // 엑티비티 추가
		
		li = (LinearLayout)findViewById(R.id.back);
		college = (Button)findViewById(R.id.college);
		school = (Button)findViewById(R.id.school);
		talk = (Button)findViewById(R.id.talk);
		ebook = (Button)findViewById(R.id.ebook);
		
		dbHelper = new DBManager(this);
		db = dbHelper.getWritableDatabase();
		
		Log.d("real", "들어옴"+ ", "+ Activity.notify_check);
		
		score_list = new ArrayList<String>();
		score_list.add("1");
		score_list.add("2");
		score_list.add("3");
		score_list.add("4");
		score_list.add("5");
		score_list.add("6");
		score_list.add("7");
		score_list.add("8");
		score_list.add("9");
		score_list.add("10");
		
		rice_adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, score_list);
		
		try{
		
		if(Activity.weather.equals("맑음")){
			li.setBackgroundResource(R.drawable.main_sunny);
		}else if(Activity.weather.equals("흐림")){
			li.setBackgroundResource(R.drawable.main_cloudy);
		}else if(Activity.weather.equals("구름 조금")){
			li.setBackgroundResource(R.drawable.main_cloudy);
		}else if(Activity.weather.equals("구름 많음")){
			li.setBackgroundResource(R.drawable.main_hard_cloudy);
		}else if(Activity.weather.equals("비")){
			li.setBackgroundResource(R.drawable.main_rain);
		}else if(Activity.weather.equals("눈/비")){
			li.setBackgroundResource(R.drawable.main_rain);
		}else if(Activity.weather.equals("눈")){
			li.setBackgroundResource(R.drawable.main_snow);
		}else if(Activity.weather.equals("구름많고 비/눈")){
			li.setBackgroundResource(R.drawable.main_snow);
		}else{
			li.setBackgroundResource(R.drawable.main_sunny);
		}
		
		}catch(NullPointerException e){
			Log.d("real", "Activity.weather null");
		}
        // GCM 서비스 등록
		
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		
		if("".equals(regId))  { //구글 가이드에는 regId.equals("")로 되어 있는데 Exception을 피하기 위해 수정
		      GCMRegistrar.register(this, "534641675187");
		}else{
		      Log.d("==============", regId);
		}
		
		// 도시락을 클릭하고 들어온 상태면
		if(Activity.notify_check == 1){
		
			handler.post(new Runnable() 
			{
				public void run()
				{
					//업데이트 완료를 핸들러로 보내줌
					handler.sendEmptyMessage(0);
				}
			});
		
		}
		
		/*
		// 식단표 파싱
			
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					
					Date today = new Date();
			    	SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); // 날짜
			    	date = format.format(today);
			    	
					
					//String food_url = "http://m.shindo.hs.kr/mobile/page/subpage/SUBPAGE_1001/main.html?siteid=sindohs&menucode=sindohs_0091&boardid=FOOD&uid=&search_date=20131216";
					String food_url = Activity.school_url+"/mobile/page/subpage/SUBPAGE_1001/main.html?siteid=sindohs&menucode=sindohs_0091&boardid=FOOD&uid=&search_date="+date;
					
					Log.e("Sdf", ""+date);
					
					URL nURL = new URL(food_url);
					
					HttpURLConnection conn = (HttpURLConnection) nURL.openConnection();

					if (conn != null) {
						conn.setRequestMethod("GET");
						conn.setDoOutput(true);

						if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
							BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "euc-kr"));

							for (int i = 0; i < 70; i++) {
								String line = br.readLine();
								
								if(i == 51 || i == 60){
									if(food_html(line) && line.length() > 10){
										
										// 점심
										if(i == 51){
											food_lunch = "점심 : " + cutting_html(line);
											Activity.food_lunch = cutting_html(line);
											
										}else{ // 저녁
																						
											food_dinner = "저녁 : " + cutting_html(line);
											Activity.food_dinner = cutting_html(line);
										}
									}
								}
							}
							
							// 저녁이 없는 날일 때
							if(food_dinner == null){
								food_dinner = "저녁 : 없음";
							}
							
							Calendar cl = Calendar.getInstance();
							cl.setTimeZone(TimeZone.getTimeZone("GMT+09:00"));
							
							Calendar current = Calendar.getInstance();
							
							
							Intent intent = new Intent(RealActivity.this, BootBroadCastReceiver.class);
							intent.putExtra("lunch", food_lunch);
							intent.putExtra("dinner", food_dinner);
							
							int hour = 18;
							int minute = 30;
							
							
							PendingIntent sender = PendingIntent.getBroadcast(RealActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
							
							AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
							am.setTimeZone("GMT+09:00");
							
							// 달같은 경우는  month가 0부터 시작한다.  
							
							cl.set(cl.get(Calendar.YEAR), cl.get(Calendar.MONTH), cl.get(Calendar.DAY_OF_MONTH), hour, minute);
							
							Log.e("asdf", cl.get(Calendar.YEAR)+","+cl.get(Calendar.MONTH) +","+ cl.get(Calendar.DAY_OF_MONTH));
							
							// 설정한 시간이 과거이면 다음날로 연장시켜준다
							if(cl.getTimeInMillis() < current.getTimeInMillis()){
								cl.set(cl.get(Calendar.YEAR), cl.get(Calendar.MONTH), cl.get(Calendar.DAY_OF_MONTH)+1, hour, minute);
							}
							
							am.setRepeating(AlarmManager.RTC_WAKEUP, cl.getTimeInMillis() , 24 * 60 * 60 * 1000, sender);
							
							
						}
					}
					
					}catch(IOException e){
						
					}
			}
		}).start();
		*/
		
		
		
		college.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent men1 = new Intent(RealActivity.this, CollegeGridActivity.class);
				startActivity(men1);
			}
		});
		
		school.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent men1 = new Intent(RealActivity.this, Webview.class);
				startActivity(men1);
			}
		});
		
		talk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent men1 = new Intent(RealActivity.this, Square_Start_Activity.class);
				startActivity(men1);
			}
		});
		
		ebook.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent men1 = new Intent(RealActivity.this, EbookActivity.class);
				startActivity(men1);
			}
		});
		
		
		
	}
	
	private final Handler handler = new Handler() //  핸들러
	{
		@Override
		public void handleMessage(Message msg)
		{
				// 도시락을 클릭하고 들어온 상태면
			
				Log.e("핸들러들어옴", "핸들러들어옴");
					
				li_rice = (LinearLayout)View.inflate(RealActivity.this, R.layout.rice, null);
				
				rice = (TextView)li_rice.findViewById(R.id.rice);
				rice.setText(Activity.food_lunch);
				
				sp = (Spinner)li_rice.findViewById(R.id.spinner1);
				rice_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				sp.setAdapter(rice_adapter);
				
				sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent, View v,
							int position, long id) {
						// TODO Auto-generated method stub
						score = ""+score_list.get(position); // 도시락 평점

					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						score = "0";
						return;
					}

				});
				
				final AlertDialog.Builder build = new AlertDialog.Builder(RealActivity.this);
				build.setView(li_rice).setPositiveButton("확인",
						new DialogInterface.OnClickListener() {

				
				public void onClick(DialogInterface dialog, int which) {
					
					WebView wv = (WebView)li_rice.findViewById(R.id.webView_rice);
					wv.getSettings().setJavaScriptEnabled(true);
					
					Date today = new Date();
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd/hh:mm:ss");
					String strDate = format.format(today);
					
					Log.e("asdf", Activity.food_lunch+", "+score+", "+Activity.school_select+", "+Activity.name+", "+ Activity.phone +", "+strDate);
					
					
					wv.loadUrl("http://hi818.cafe24.com/StudyProject/Realschool/real_riceinput.jsp?&rice="+Activity.food_lunch+"&score="+score+"&school="+Activity.school_select+"&name="+Activity.name+"&phone="+Activity.phone +"&date="+strDate);
					
					Toast.makeText(RealActivity.this, "평점을 체크했습니다.^^", Toast.LENGTH_SHORT).show();
					
				}
			})
			.setTitle("평점")
			.setMessage("식단에 대한 \n 평점을 남기면 point를 받을 수 있습니다.^^")
			.show();
				
			Activity.notify_check = 0;
			}							
	};
	
	

	public String cutting_html(String line){
		return line.trim().substring(line.indexOf(">"),	line.lastIndexOf("<")-1);
	}
	
	public boolean food_html(String line){
		
		boolean word_check = false;
		
		if(line.trim().substring(0,	line.indexOf(">")).equals("<td style=\"padding-top:3px; padding-bottom:3px;\">")){
			word_check = true;
		}
		
		return word_check;
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	 @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        
	            case R.id.alarm:
	                Intent intent = new Intent(this, com.example.testalram.AlarmClock.class);
	                startActivity(intent);
	                return true;

	            case R.id.bantalk:
	                return true;
	                
	            case R.id.db:
	            	db.execSQL("delete from data;");
	                return true;

	        }

	        return super.onOptionsItemSelected(item);
	    }
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			final AlertDialog.Builder build = new AlertDialog.Builder(this);
			build.setPositiveButton("확인",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							for (int i = 0; i < Activity.at.size(); i++) {
								Activity.at.get(i).finish();
							}

							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					})
					.setTitle("종료")
					.setMessage(
							"리얼스쿨을 종료하시겠습니까?")
					.setNegativeButton("취소",
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
					}).show();

		}
		return false;
	}

}
